package servlet;

import beans.ModelBean;
import java.io.*;
import java.util.*;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.*;
import javax.servlet.http.*;

public class AddModelServlet extends HttpServlet {

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String id = "";
        String name = "";
        String type = "";
        String company = "";
        String scale = "";
        String price = "";
        String quantity = "";
        String description = null;
        String fileName1 = null;
        String imageURL = null;
        boolean ok = false;

        try {

            //todo: use new version http://commons.apache.org/fileupload/using.html

            DiskFileUpload fu = new DiskFileUpload();

            fu.setSizeThreshold(4096);
            fu.setSizeMax(1000000);
            //fu.setRepositoryPath(application.getRealPath("/") + "images/");
            //out.println(fu.getRepositoryPath());

            List fileItems = fu.parseRequest(request);

            Iterator itr = fileItems.iterator();
            ArrayList<String> image = new ArrayList<String>();
            String[] finalImage = new String[0];
            while (itr.hasNext()) {
                FileItem fi = (FileItem) itr.next();
                if (fi.isFormField()) {
                    String fieldName = fi.getFieldName();
                    out.println(fi.getString() + "<br>");
                    if (fieldName.equals("itemID")) {
                        id = fi.getString();
                        out.println("ItemID: " + id + "<br>");
                    }
                    if (fieldName.equals("name")) {
                        name = fi.getString();
                        out.println("Name: " + name + "<br>");
                    }
                    if (fieldName.equals("type")) {
                        type = fi.getString();
                        out.println("Type: " + type + "<br>");
                    }
                    if (fieldName.equals("company")) {
                        company = fi.getString();
                        out.println("Company: " + company + "<br>");
                    }
                    if (fieldName.equals("scale")) {
                        scale = fi.getString();
                        out.println("Scale: " + scale + "<br>");
                    }
                    if (fieldName.equals("price")) {
                        price = fi.getString();
                        out.println("Price: " + price + "<br>");
                    }
                    if (fieldName.equals("quantity")) {
                        quantity = fi.getString();
                        out.println("Quantity: " + quantity + "<br>");
                    }
                    if (fieldName.equals("description")) {
                        description = fi.getString();
                    }

                } else {
                    String fieldName = fi.getFieldName();
                    if (fieldName.equals("image1")) {
                        if (!"".equals(fi.getName())) {
                            image.add(fi.getName());
                            out.println(fi.getName());
                            out.println("SIZE: " + fi.getSize());
                            ModelBean.uploadImage(fi);
                        }
                    } else if (fieldName.equals("image2")) {
                        if (!"".equals(fi.getName())) {
                            image.add(fi.getName());
                            out.println(fi.getName());
                            out.println("SIZE: " + fi.getSize());
                            ModelBean.uploadImage(fi);
                        }
                    } else if (fieldName.equals("image3")) {
                        if (!"".equals(fi.getName())) {
                            image.add(fi.getName());
                            out.println(fi.getName());
                            out.println("SIZE: " + fi.getSize());
                            ModelBean.uploadImage(fi);
                        }
                    } else if (fieldName.equals("image4")) {
                        if (!"".equals(fi.getName())) {
                            image.add(fi.getName());
                            out.println(fi.getName());
                            out.println("SIZE: " + fi.getSize());
                            ModelBean.uploadImage(fi);
                        }
                    } else {

                        out.println(fi.getName());
                        out.println("SIZE: " + fi.getSize());
                        fileName1 = ModelBean.uploadImage(fi);
                        ok = true;
                    }
                /*
                out.println(fi.getName());
                out.println("SIZE: "+fi.getSize());
                
                String name1 = fi.getName();
                name1 = name1.replace('\\', '/' );
                StringTokenizer token = new StringTokenizer(name1, "/");
                while (token.hasMoreTokens()) {
                fileName1 = token.nextToken();
                }
                
                //String fNew2 = fNew.getAbsolutePath();
                out.println(fileName1);
                String fileName2 = fileName1.toLowerCase();
                //fileName1.endsWith(".jpg")
                if (fileName2.endsWith("jpg") ||
                fileName2.endsWith("gif") ||
                fileName2.endsWith("jpeg")) {
                //File f= new File(application.getRealPath("/"), fileName1);
                //File f = new File("C:/FYPimage", fileName1);
                
                File f = new File("C:\\Program Files\\Apache Software Foundation\\Tomcat 5.0\\webapps\\image", fileName1);
                
                fi.write(f);
                ok = true;
                } else {
                out.println("Error: the image must be in jpg, jpeg or gif format");
                ok = false;
                // return;
                }
                 */
                }//end else
            }//end while
            if (ok) {
                int itemID = ModelBean.create(id, fileName1, name, description, price, scale, company, type, quantity);
                if (itemID == -1) {
                }
                finalImage = (String[]) image.toArray(finalImage);
                if (finalImage.length > 0) {
                    for (int i = 0; i < finalImage.length; i++) {
                        int insertImage = ModelBean.insertImageLink(itemID + "", finalImage[i]);
                    }
                }
                request.getSession().setAttribute("complete_msg", "Add Model Information Complete");
                response.sendRedirect("completePage.jsp");
            }
        } catch (Exception e) {
            response.sendRedirect("ErrorPage.jsp");
        }


    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}
